<!--
 * @Author: gao_m3
 * @Date: 2021-06-21 10:08:14
 * @LastEditors: zhong_m
 * @LastEditTime: 2022-02-11 11:34:00
 * @Descripttion: 
-->
<template>
  <fks-dialog
    title="logo上传"
    :visible.sync="isShow"
    append-to-body
    :close-on-click-modal="false"
    @close="$emit('update:visible', false)"
  >
    <div class="wrapper">
      <div class="left">
        <vueCropper
          ref="cropper"
          :img="option.image || 'static/img/logo.png'"
          :auto-crop="option.autoCrop"
          :info="option.info"
          :full="option.full"
          :output-type="option.outputType"
          :fixed-box="option.fixedBox"
          :can-move-box="option.canMoveBox"
          :can-move="option.canMove"
          :auto-crop-width="option.autoCropWidth"
          :auto-crop-height="option.autoCropHeight"
          :output-size="option.outputSize"
          :center-box="option.centerBox"
          @realTime="realTime"
        />
        <div class="changeImage">
          <!-- <i class="fks-icon-upload-line" for="uploads"></i> -->
          <label
            class="btn"
            for="uploads"
          >{{ LANG.SELECT_PICTURE }}</label>
          <input
            id="uploads"
            ref="uploads"
            type="file"
            style="display: none;"
            accept="image/png, image/jpeg, image/gif, image/jpg"
            @change="setImage($event, 1)"
          >
        </div>
      </div>
      <fks-divider
        direction="vertical"
        class="divider"
      />
      <div class="right">
        <div class="preview">
          <div class="img-container">
            <div
              ref="iconBox"
              class="icon-box"
              :style="{ transform: `translateX(${iconOffset}px)` }"
              @mousedown="iconBoxMousedown"
            />
            <img
              :src="previews.url"
              :style="previews.img"
            >
          </div>
          <div class="tips">
            {{ LANG.PREVIEW_LOGO_TIPS }}
          </div>
          <p class="preview_text">
            {{ LANG.PREVIEW_PICTURE }}
          </p>

          <fks-button
            :disabled="!option.image"
            type="primary"
            class="sure_button"
            @click="avatarUpload()"
          >
            {{ LANG.DETERMINE }}
          </fks-button>

          <div />
        </div>
      </div>
    </div>
  </fks-dialog>
</template>

<script>
import { VueCropper } from 'vue-cropper'
import { uploadFile } from '@/api/file'

export default {
  name: 'LogoUpload',
  components: {
    VueCropper
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    logo: {
      type: String,
      default: ''
    },
    logoIconOffset: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      fileList: [], // 用来存放图片（用来装饰）
      previews: {},
      fileUpload: {},
      option: {
        image: this.logo,
        autoCrop: true,
        info: true,
        full: false,
        outputType: 'png',
        fixedBox: true,
        canMoveBox: false,
        canMove: true,
        fixed: true,
        autoCropWidth: 200,
        autoCropHeight: 56,
        outputSize: 1,
        centerBox: false
      },
      iconOffset: 0
    }
  },
  computed: {
    isShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    logoIconOffset: {
      handler(val) {
        this.iconOffset = val
      },
      immediate: true
    }
  },
  mounted() {
    let onKeydown = (e) => {
      if(e.keyCode === 37) {
        this.iconOffset --
      } else if (e.keyCode === 39) {
        this.iconOffset ++
      }
    }
    document.addEventListener('keydown', onKeydown)
    this.$once('hook:beforeDestory', () => {
      document.removeEventListener('keydown', onkeydown)
    })
  },
  methods: {
    iconBoxMousedown(e) {
      let x = e.pageX - this.iconOffset
      let firstTime = new Date().getTime()
      document.onmousemove = (e) => {
        this.iconOffset = e.pageX - x
      }
      document.onmouseup = (e) => {
        document.onmousemove = document.onmouseup = null
        if (new Date().getTime() - firstTime > 200) {
          e.stopPropagation()
        }
      }
    },
    setImage(e, num) {
      let file = e.target.files[0]
      this.fileUpload = file
      if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
        this.$message.warning('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种')
        return false
      }
      let reader = new FileReader()
      reader.onload = (e) => {
        let data
        if (typeof e.target.result === 'object') {
          // 把Array Buffer转化为blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]))
        } else {
          data = e.target.result
        }
        if (num === 1) {
          this.option.image = data
        }
        this.$refs['uploads'].value = ''
      }

      reader.readAsArrayBuffer(file)
    },
    // 放大缩小
    changeScale(num) {
      num = num || 1
      this.$refs.cropper.changeScale(num)
    },
    // 左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft()
    },
    // 右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight()
    },
    // 预览
    realTime(data) {
      this.previews = {
        ...data
      }
    },
    avatarUpload() {
      this.$refs.cropper.getCropData((data) => {
        let binaryData = this.dataURLtoFile(
          data,
          this.fileUpload.name || 'avatar.jpg'
        )
        //等待logo上传成功后才能进行保存
        let formData = new FormData()
        formData.append('file', binaryData)

        uploadFile(formData)
          .then((res) => {
            if (res.status) {
              this.$emit(
                'update:logo',
                '/sys-storage/download_image?f8s=' + res.data.fileToken
              )
              this.$emit('update:logoIconOffset', this.iconOffset)
              this.$emit('update:visible', false)
            } else {
              this.$message.error('logo上传失败：' + res.message)
            }
          })
          .catch((error) => {})
      })
    },
    dataURLtoFile(dataurl, filename) {
      //将base64转换为文件
      let arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, { type: mime })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .cropper-crop-box {
  overflow: hidden;
  transform: translate3d(0, 84px, 0);
}

::v-deep .cropper-modal {
  position: relative;
  width: 200px;
  height: 200px;
  overflow: hidden;
  // background: #bdbdbd00;
  box-shadow: 1px 1px 8px grey;
}

// ::v-deep .cropper-modal::after {
//   $lineStart: 4%;
//   $lineEnd: 96%;
//   $bgStart: 25%;
//   $bgEnd: 75%;
//   $color: #ddd;

//   content: '';
//   position: absolute;
//   top: -50%;
//   left: -50%;
//   width: 200%;
//   height: 200%;
//   background-image: /* 前两个渐变是为了防止 rotate 之后的分割线 */ linear-gradient(
//     0deg,
//     $color $lineStart,
//     transparent $lineStart,
//     transparent $lineEnd,
//     $color $lineEnd
//   ), linear-gradient(
//     -90deg,
//     $color $lineStart,
//     transparent $lineStart,
//     transparent $lineEnd,
//     $color $lineEnd
//   ), linear-gradient(
//     45deg,
//     $color $bgStart,
//     transparent $bgStart,
//     transparent $bgEnd,
//     $color $bgEnd
//   ), linear-gradient(
//     -45deg,
//     $color $bgStart,
//     transparent $bgStart,
//     transparent $bgEnd,
//     $color $bgEnd
//   );
//   background-size: 15px 15px;
//   transform: rotate(45deg);
// }

// ::v-deep .cropper-face {
//   background: black;
//   opacity: .3;
// }

::v-deep .fks-dialog__body {
  height: 228px;
}

// .vue-cropper {
//   background-image: none;
// }

.wrapper {
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 200px;
}

.left {
  flex: 0 0 200px;
  width: 200px;
  height: 100%;
  margin-left: 14%;
  .btn {
    display: inline-block;
    // width: 100%;
    margin: 4% 0 0 36%;
    cursor: pointer;

    &:hover {
      color: #005fe1;
    }
  }
}

.divider {
  height: 200px;
  margin-left: 14%;
}

.right {
  width: 304px;
  margin: auto;

  .preview {
    width: 100%;
    height: 120px;
    margin-top: 12%;

    .img-container {
      position: relative;
      width: 200px;
      height: 56px;
      margin: auto;
      border: 1px solid #ddd;
      overflow: hidden;
      background: var(--theme-color);
      .icon-box {
        position: absolute;
        z-index: 9;
        width: 54px;
        height: 54px;
        border: 1px dashed #ddd;
      }
    }

    // ::v-deep .img-container::before {
    //   content: '';
    //   position: absolute;
    //   z-index: 100;
    //   top: 0;
    //   left: 54px;
    //   display: block;
    //   width: 1px;
    //   height: 56px;
    //   border-left: 1px dashed #ddd;
    // }

    .preview_text {
      margin: 6% 0 0 40%;
      font-size: 12px;
    }

    .tips {
      margin-top: 20px;
      text-align: center;
      color: #8b8484;
    }

    .sure_button {
      width: 100px;
      margin-top: 5%;
      margin-left: 86%;
    }
  }
}

.button-box {
  display: flex;
  justify-content: center;
  width: 500px;
  margin-top: 16px;
}

.button-box-right {
  margin-top: 16px;
  margin-left: 20px;
  text-align: center;

  button {
    width: 200px;
  }
}
</style>
